//
//  YYEExampleTableView.m
//  YuYingEDU
//
//  Created by zl on 2018/3/13.
//  Copyright © 2018年 胡波. All rights reserved.
//

#import "YYEExampleView.h"
#import "YYEExampleCell.h"
#import "YYEExampleCell1.h"
#import "TPKeyboardAvoidingScrollView.h"
#import "TYAttributedLabel.h"
#import "RegexKitLite.h"
#import "TExamTextField.h"

#define kExamTextFieldWidth 150
#define kExamTextFieldHeight 20
#define kAttrLabelWidth (kScreenWidth-20)
#define kTextFieldTag 1000

@interface YYEExampleView ()

@property (nonatomic,strong) YYEBaseTableView  *tableview;
@property(nonatomic,assign) NSInteger page;

@property (nonatomic,strong) UIView *headerView;
@property (nonatomic,strong) UILabel *label;
@property (nonatomic,strong) UILabel *scorelabel;

@property (nonatomic,strong) UIView *footerView;
@property (nonatomic,strong) UIButton *okBtn;
@property (nonatomic,strong) UILabel *oklabel;

@property (nonatomic,strong) UILabel *answerlabel;
@property (nonatomic,strong) UILabel *reasonlabel;

@property (nonatomic,strong) NSMutableArray *selectArrM;


@property (nonatomic,strong) TYAttributedLabel *attLabel;
@property (nonatomic,strong) TYTextContainer *textContainer;
@property (nonatomic,strong) NSAttributedString *attString;
@property (nonatomic,weak) TPKeyboardAvoidingScrollView *scrollView;




@end

@implementation YYEExampleView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        
        
        [self configUI];
        
        [self addScrollView];
        
        [self addTextAttributedLabel];
    }
    return self;
}

- (void)addScrollView
{
    TPKeyboardAvoidingScrollView *scrollView = [[TPKeyboardAvoidingScrollView alloc]initWithFrame:self.bounds];
    [self addSubview:scrollView];
    _scrollView = scrollView;
}

- (void)configUI {

    [self addSubview:self.tableview];
    
    self.tableview.backgroundColor = GeneralBackColor;
    self.tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.tableview registerClass:[YYEExampleCell class] forCellReuseIdentifier:@"cell"];
    [self.tableview registerClass:[YYEExampleCell1 class] forCellReuseIdentifier:@"cell1"];

    self.tableview.frame = self.bounds;

    // 头视图
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 0)];
    self.headerView = headerView;
    self.tableview.tableHeaderView = headerView;
    
    UILabel *label = [UILabel labelWithframe:CGRectZero text:nil font:[UIFont systemFontOfSize:15] textAlignment:0 textColor:@"#030303"];
    [headerView addSubview:label];
    label.numberOfLines = 0;
    self.label = label;
    
    UILabel *scorelabel = [UILabel labelWithframe:CGRectZero text:nil font:[UIFont systemFontOfSize:17] textAlignment:NSTextAlignmentCenter textColor:@"#999999"];
    [headerView addSubview:scorelabel];
    self.scorelabel = scorelabel;
    
    // 尾视图
    UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 0)];
    self.footerView = footerView;
    self.tableview.tableFooterView = footerView;
    
    UIButton *okBtn = [UIButton buttonWithframe:CGRectZero text:@"确定" font:SystemFont(18) textColor:@"#000000" backgroundColor:@"#0A59E2" normal:nil selected:nil];
    [footerView addSubview:okBtn];
    okBtn.backgroundColor = [UIColor grayColor];
    okBtn.userInteractionEnabled = NO;
    self.okBtn = okBtn;
    [okBtn addTarget:self action:@selector(okAction) forControlEvents:UIControlEventTouchUpInside];
    
    UILabel *oklabel = [UILabel labelWithframe:CGRectZero text:nil font:[UIFont systemFontOfSize:16] textAlignment:0 textColor:@"#D0021B"];
    [footerView addSubview:oklabel];
    self.oklabel = oklabel;

    UILabel *answerlabel = [UILabel labelWithframe:CGRectZero text:nil font:[UIFont systemFontOfSize:16] textAlignment:0 textColor:@"#D0021B"];
    [footerView addSubview:answerlabel];
    self.answerlabel = answerlabel;
    
    UILabel *reasonlabel = [UILabel labelWithframe:CGRectZero text:nil font:[UIFont systemFontOfSize:16] textAlignment:0 textColor:@"#D0021B"];
    [footerView addSubview:reasonlabel];
    self.reasonlabel = reasonlabel;
    reasonlabel.numberOfLines = 0;


}

- (void)okAction
{
    [self compareAnswer];
}

- (YYEBaseTableView *)tableview {
    
    if (!_tableview) {
        _tableview = [[YYEBaseTableView alloc]initwithDelegate:self];
    }
    return _tableview;
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return _model.choice.count;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    ChoiceModel *model = _model.choice[indexPath.row];
    if (_model.questionType.integerValue == 4) {
//        questionType = @"填空";
        return model.cellHeight;

        
    } else if (_model.questionType.integerValue == 5) {
//        questionType = @"简答";
        return model.cellHeight;

    } else {
        
        //    model.opt = @"dskksdfhjsdkfjsfsalfsajflskjklscnxsmvhdsijfhdsjkfhdsfjihsdfjsdhfjsehfjsdkhfsjdk";

        if (model.cellHeight > 46) {
            return model.cellHeight;
        }
        else {
            return 46;
            
        }
    }
    

}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (_model.questionType.integerValue == 4||
        _model.questionType.integerValue == 5) {
        
        YYEExampleCell1 *cell = [tableView dequeueReusableCellWithIdentifier:@"cell1"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.questionType = _model.questionType;
        cell.model = _model.choice[indexPath.row];
        return cell;
        
        
    } else {
        YYEExampleCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.row = indexPath.row;
        cell.model = _model.choice[indexPath.row];
        cell.userInteractionEnabled = !_model.isTouch;
        return cell;
    }

    
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if ([_model.questionType isEqualToString:@"4"] || [_model.questionType isEqualToString:@"5"]) {
        
        // -----填空和简答-----
        
    }
    else {
        // -----多选、判断、单选-----

        ChoiceModel *cModel = _model.choice[indexPath.row];
        cModel.isChoose = !cModel.isChoose;
        
        if ([_model.questionType isEqualToString:@"1"] || [_model.questionType isEqualToString:@"3"]) {
            
            [self compareAnswer];
        }
        else {
            
            // 是否选择过
            BOOL isChoose = NO;
            for (ChoiceModel *cModel1 in _model.choice) {
                
                if (cModel1.isChoose) {
                    isChoose = YES;
                    break;
                }
                
            }
            if (isChoose) {
                self.okBtn.backgroundColor = [UIColor colorWithHexString:@"#0A59E2"];
                self.okBtn.userInteractionEnabled = YES;
            }
            else {
                
                self.okBtn.backgroundColor = [UIColor colorWithHexString:@"#999999"];
                self.okBtn.userInteractionEnabled = NO;
            }
            
            [tableView reloadData];
        }
    }
    
    
}

- (void)compareAnswer
{
    _model.isTouch = YES;

    // 选的答案
    NSMutableArray *selectArrM = [NSMutableArray array];
    self.selectArrM = selectArrM;
    for (ChoiceModel *cModel1 in _model.choice) {
        if (cModel1.isChoose) {
            [selectArrM addObject:cModel1.sort];
        }
        else {
            [selectArrM removeObject:cModel1.sort];
            
        }
    }
    NSArray *result = [selectArrM sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
        
        NSLog(@"%@~%@",obj1,obj2); //3~4 2~1 3~1 3~2
        
        return [obj1 compare:obj2]; //升序
        
    }];
    
    NSLog(@"result=%@",result);
    NSString *selectAnswer = [result componentsJoinedByString:@","];
    NSLog(@"selectAnswer=%@",selectAnswer);
    
    // 原答案
    NSString *okAnswer = [_model.answer componentsJoinedByString:@","];
    NSLog(@"okAnswer=%@",okAnswer);
    
    // 比较答案
    if ([selectAnswer isEqualToString:okAnswer]) {
        
        _model.answerType = @"1";
        
        if (self.block) {// 答对回调
            self.block();
        }
    }
    else {
        
        
        _model.answerType = @"2";
        
        if (self.block1) {// 答错回调
            self.block1();
        }
        
        
    }
    [self setModel:_model page:_page];
}

- (void)setModel:(YYEExampleModel *)model page:(NSInteger)page
{
    _model = model;
    _page = page;
    
    // 头视图
    NSString *questionType = nil;
    if (model.questionType.integerValue == 1) {
        questionType = @"单选";
    } else if (model.questionType.integerValue == 2) {
        questionType = @"多选";
    } else if (model.questionType.integerValue == 3) {
        questionType = @"判断";
    } else if (model.questionType.integerValue == 4) {
        questionType = @"填空";

    } else if (model.questionType.integerValue == 5) {
        questionType = @"简答";

    }

    NSString *questionlabelText = [NSString stringWithFormat:@"%ld.%@ %@", page, questionType, model.question];
    
    if (model.questionType.integerValue == 4) {// @"填空";
        
        NSMutableArray *arrM = [NSMutableArray array];
        if (model.choice.count == 0) {
            
            for (int i=0; i<model.answerF.count; i++) {
                ChoiceModel *cModel = [[ChoiceModel alloc] init];
                [arrM addObject:cModel];
            }
            model.choice = arrM;
            
        }
        
        self.tableview.hidden = YES;
        self.scrollView.hidden = NO;

        questionlabelText = [questionlabelText stringByReplacingOccurrencesOfString:@"___" withString:@"[@]"];
        [self createTextContainer:questionlabelText questionType:questionType];
    }
    else {

        self.tableview.hidden = NO;
        self.scrollView.hidden = YES;
        
        NSString *pageLength = [NSString stringWithFormat:@"%ld",page];
        
        NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
        [paragraphStyle setLineSpacing:4.0f];
        NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:questionlabelText];
        NSDictionary *attrs = [NSDictionary dictionaryWithObjectsAndKeys:[UIColor colorWithHexString:@"#D0021B"], NSForegroundColorAttributeName, nil];
        [attributedString setAttributes:attrs range:NSMakeRange(pageLength.length+1, [questionType length])];
        [attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [questionlabelText length])];
        NSDictionary *dic = @{NSFontAttributeName:[UIFont systemFontOfSize:15.f], NSParagraphStyleAttributeName:paragraphStyle};
        CGFloat questionLabelH = [questionlabelText boundingRectWithSize:CGSizeMake(SCREEN_WIDTH-26, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil].size.height;
        _label.attributedText = attributedString;
        
        self.scorelabel.text = [NSString stringWithFormat:@"(%@分)",model.score];
        
        self.label.frame = CGRectMake(13, 11, SCREEN_WIDTH-26, questionLabelH);
        self.scorelabel.frame = CGRectMake(SCREEN_WIDTH-12-60, self.label.frame.origin.y+ self.label.frame.size.height, 60, 20);
        
        self.headerView.frame = CGRectMake(0, 0, SCREEN_WIDTH,self.label.frame.origin.y+ self.label.frame.size.height+22);
        self.tableview.tableHeaderView = self.headerView;
        
        
        if ([_model.questionType isEqualToString:@"5"]) {
            // -----简答-----
            
            NSMutableArray *arrM = [NSMutableArray array];
            if (model.choice.count == 0) {
                
                for (int i=0; i<model.answerF.count; i++) {
                    ChoiceModel *cModel = [[ChoiceModel alloc] init];
                    [arrM addObject:cModel];
                }
                model.choice = arrM;
                
            }
            self.tableview.tableFooterView = nil;
            
        }
        else {
            
            // -----多选、判断、单选-----
            
            if ([_model.questionType isEqualToString:@"2"]) {// 多选
                self.okBtn.hidden = NO;
                self.okBtn.frame = CGRectMake(25, 0, SCREEN_WIDTH-50, 40);
                self.oklabel.frame = CGRectMake(self.okBtn.jc_x, self.okBtn.jc_bottom+30, self.okBtn.jc_width, 20);
                
                // 是否确定过
                if (model.isTouch) {
                    
                    self.okBtn.backgroundColor = [UIColor colorWithHexString:@"#999999"];
                    self.okBtn.userInteractionEnabled = NO;
                }
                else {
                    
                    // 是否选择过
                    BOOL isChoose = NO;
                    for (ChoiceModel *cModel1 in _model.choice) {
                        
                        if (cModel1.isChoose) {
                            isChoose = YES;
                            break;
                        }
                        
                    }
                    if (isChoose) {
                        self.okBtn.backgroundColor = [UIColor colorWithHexString:@"#0A59E2"];
                        self.okBtn.userInteractionEnabled = YES;
                    }
                    else {
                        
                        self.okBtn.backgroundColor = [UIColor colorWithHexString:@"#999999"];
                        self.okBtn.userInteractionEnabled = NO;
                    }
                }
                
                
            }
            else {
                
                self.okBtn.hidden = YES;
                self.oklabel.frame = CGRectMake(25, 0, SCREEN_WIDTH-50, 20);
                
            }
            self.answerlabel.frame = CGRectMake(self.oklabel.jc_x, self.oklabel.jc_bottom+10, self.oklabel.jc_width, 20);
            self.reasonlabel.frame = CGRectMake(self.answerlabel.jc_x, self.answerlabel.jc_bottom+10, self.answerlabel.jc_width, 20);
            
            self.footerView.frame = CGRectMake(0, 0, SCREEN_WIDTH,self.reasonlabel.jc_bottom);
            
            if ([model.answerType isEqualToString:@"1"]) {
                self.oklabel.text = @"回答正确";
                
                self.oklabel.hidden = NO;
                self.answerlabel.hidden = NO;
                self.reasonlabel.hidden = NO;
                
                self.oklabel.textColor = [UIColor colorWithHexString:@"#19B260"];
                self.answerlabel.textColor = [UIColor colorWithHexString:@"#19B260"];
                self.reasonlabel.textColor = [UIColor colorWithHexString:@"#19B260"];

                
            } else if ([model.answerType isEqualToString:@"2"]) {
                self.oklabel.text = @"回答错误";
                
                self.oklabel.hidden = NO;
                self.answerlabel.hidden = NO;
                self.reasonlabel.hidden = NO;
                
                self.oklabel.textColor = [UIColor colorWithHexString:@"#D0021B"];
                self.answerlabel.textColor = [UIColor colorWithHexString:@"#D0021B"];
                self.reasonlabel.textColor = [UIColor colorWithHexString:@"#D0021B"];

            } else {
                
                self.oklabel.hidden = YES;
                self.answerlabel.hidden = YES;
                self.reasonlabel.hidden = YES;

            }
            
            for (int i=0; i<model.choice.count; i++) {
                
                ChoiceModel *cModel = model.choice[i];
                
                if (i == 0) {
                    cModel.letter = @"A";
                }
                if (i == 1) {
                    cModel.letter = @"B";
                    
                }
                if (i == 2) {
                    cModel.letter = @"C";
                    
                }
                if (i == 3) {
                    cModel.letter = @"D";
                    
                }
                if (i == 4) {
                    cModel.letter = @"E";
                    
                }
                if (i == 5) {
                    cModel.letter = @"F";
                    
                }
                if (i == 6) {
                    cModel.letter = @"G";
                    
                }
            }
            
            NSMutableArray *arrM = [NSMutableArray array];
            for (NSString *answer in model.answer) {
                
                for (ChoiceModel *cModel in model.choice) {
                    
                    if (model.isTouch) {
                        
                        if (answer.integerValue == cModel.sort.integerValue) {
                            [arrM addObject:cModel.letter];
                        }
                    }
                    
                }
            }
            
            NSArray *result = [arrM sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
                
                NSLog(@"%@~%@",obj1,obj2); //3~4 2~1 3~1 3~2
                
                return [obj1 compare:obj2]; //升序
                
            }];
            NSString *selectAnswer = [result componentsJoinedByString:@" "];
            //    self.answerlabel.text = @"正确答案：C";
            self.answerlabel.text = [NSString stringWithFormat:@"正确答案：%@",selectAnswer];
            self.reasonlabel.text = @"原因：因为........";
            
            // "type": 2, // 1是习题 2是考试
            if (self.type.integerValue == 2) {
                
                if (self.process.integerValue == 3) {

                    self.tableview.tableFooterView = self.footerView;

                }
                else {
                    _tableview.tableFooterView = nil;

                }
            }
        }
        
        [_tableview reloadData];
    }
    
}
        
//  ---------填空------------
- (void)createTextContainer:(NSString *)text questionType:(NSString *)questionType
{
    // 属性文本生成器
    TYTextContainer *textContainer = [[TYTextContainer alloc]init];
    textContainer.text = text;
    
    // 整体设置属性
    textContainer.linesSpacing = 2;
    textContainer.paragraphSpacing = 2;
    
    // 文字样式
    TYTextStorage *textStorage = [[TYTextStorage alloc]init];
    textStorage.range = [text rangeOfString:questionType];
    textStorage.textColor = [UIColor colorWithHexString:@"#D0021B"];
    [textContainer addTextStorage:textStorage];
    
    // 填空题
    NSArray *blankStorage = [self.class parseTextFieldsWithString:text];
    [textContainer addTextStorageArray:blankStorage];
    
    // 生成 NSAttributedString
    //_attString = [textContainer createAttributedString];
    
    // 或者 生成 TYTextContainer
    _textContainer = [textContainer createTextContainerWithTextWidth:kAttrLabelWidth];
    
    //////////
    _attLabel.textContainer = _textContainer;
    
    // 或者设置 attString
    //label.attributedText = _attString;
    
    [_attLabel sizeToFit];
    
    [_scrollView setContentSize:CGSizeMake(0, CGRectGetMaxY(_attLabel.frame)+10)];
    
    __typeof (self) __weak weakSelf = self;
    [self enumerateTextFieldStorageUseBlock:^(TYViewStorage *viewStorage) {
        [weakSelf resetTextFieldState:(TExamTextField *)viewStorage.view];
    }];
}

// 重置textfield
- (void)resetTextFieldState:(TExamTextField *)textField
{
    ChoiceModel *model = _model.choice[textField.tag];
    textField.model = model;
}

// 解析填空
+ (NSArray *)parseTextFieldsWithString:(NSString *)string
{
    
    NSMutableArray *textFieldArray = [NSMutableArray array];
    [string enumerateStringsMatchedByRegex:@"\\[@\\]" usingBlock:^(NSInteger captureCount, NSString *const __unsafe_unretained *capturedStrings, const NSRange *capturedRanges, volatile BOOL *const stop) {
        
        if (captureCount > 0) {
            
//            10.0/255, 89.0/255, 226.0/255
            TExamTextField *textField = [[TExamTextField alloc]initWithFrame:CGRectMake(0, 0, kExamTextFieldWidth, kExamTextFieldHeight)];
            textField.textColor = [UIColor colorWithRed:10.0/255 green:89.0/255 blue:226.0/255 alpha:1];
            textField.textAlignment = NSTextAlignmentCenter;
            textField.font = [UIFont systemFontOfSize:15];
            textField.tag = textFieldArray.count;

            TYViewStorage *viewStorage = [[TYViewStorage alloc]init];
            viewStorage.range = capturedRanges[0];
            viewStorage.view = textField;
            viewStorage.tag = kTextFieldTag + textFieldArray.count;
            
            [textFieldArray addObject:viewStorage];
        }
    }];
    
    return textFieldArray.count > 0 ?[textFieldArray copy] : nil;
}

- (void)addTextAttributedLabel
{
    TYAttributedLabel *label = [[TYAttributedLabel alloc]initWithFrame:CGRectMake(10, 11, kAttrLabelWidth, 0)];
    [_scrollView addSubview:label];
    _attLabel = label;
//    label.delegate = self;
    

}


// 遍历出 textfiled
- (void)enumerateTextFieldStorageUseBlock:(void(^)(TYViewStorage *viewStorage))block
{
    for (TYTextStorage *textStorage in _textContainer.textStorages) {
        if ([textStorage isKindOfClass:[TYViewStorage class]]) {
            TYViewStorage *viewStorage = (TYViewStorage *)textStorage;
            if ([viewStorage.view isKindOfClass:[TExamTextField class]]) {
                if (block) {
                    block(viewStorage);
                }
            }
        }
    }
}

@end
